package xyz.csmcool.imuser.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.csmcool.imuser.entity.Users;
import xyz.csmcool.imuser.entity.vo.*;
import xyz.csmcool.imuser.feignclient.RoomClient;
import xyz.csmcool.imuser.mapper.UsersMapper;
import xyz.csmcool.imuser.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.csmcool.imutil.ExceptionHandler.CommonException;
import xyz.csmcool.imutil.dto.RoomUserDto;
import xyz.csmcool.imutil.dto.RoomUsersDto;
import xyz.csmcool.imutil.dto.UserDto;
import xyz.csmcool.imutil.utils.BeanUtil;
import xyz.csmcool.imutil.utils.CodeUtil;
import xyz.csmcool.imutil.utils.MailUtils;
import xyz.csmcool.imutil.utils.SecretUtils;
import xyz.csmcool.imutil.webVo.MyPage;
import xyz.csmcool.imutil.webVo.ResultCode;
import xyz.csmcool.imutil.webVo.ResultVo;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author csmcool
 * @since 2022-07-31
 */
@Service
@RequiredArgsConstructor
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

   final UsersMapper usersMapper;
   final RoomClient roomClient;

    @Override
    public Integer isSuccessLogin(UserLoginVo userLoginVo) {
        String encrypt = SecretUtils.encrypt(userLoginVo.getPassword());
        Integer id = usersMapper.selectIdByEmail(userLoginVo.getEmail());
        return id;
    }

    @Override
    public Users isSuccessLoginAndBackInfo(UserLoginVo userLoginVo) {
        String encrypt = SecretUtils.encrypt(userLoginVo.getPassword());
        Users users = usersMapper.selectUserInfoByEmailAndPassword(userLoginVo.getEmail(), encrypt);
        return users;
    }

    @Override
    public Boolean registerNewUser(UserRegisterVo userRegisterVo) {

        //查询email是否存在
        Integer id = usersMapper.selectIdByEmail(userRegisterVo.getEmail());
        if (id != null) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(892).setMessage("邮箱已被注册，请更换邮箱"));
        }
        //添加新用户
        String encrypt = SecretUtils.encrypt(userRegisterVo.getPassword());
        String code = CodeUtil.getCheckCode();
        Boolean insertNewUser = usersMapper.insertNewUser(userRegisterVo.getUsername(), encrypt, userRegisterVo.getEmail(),code);
        if (!insertNewUser) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(504).setMessage("注册出了点小插曲，请稍候重试"));
        }
        //发送激活邮件
        String activeSrc = "http://localhost:3000/active?email=" + userRegisterVo.getEmail() + "&code=" + code;
        MailUtils.sendMail(userRegisterVo.getEmail(),"当前你正在激活邮箱，如非本请忽略该邮件，激活邮箱请点击链接" + activeSrc,"加入什锦聊天室");
        return true;
    }

    @Override
    public Boolean isSameEmail(String email) {
        Integer id = usersMapper.selectIdByEmail(email);
        return id != null;
    }

    @Override
    public Boolean updateUserPassword(Integer id, String password) {
        return usersMapper.updateUserPassword(id,password);
    }

    @Override
    public Boolean activeEmail(String email, String code) {
        Boolean aBoolean = usersMapper.activeEmail(email, code);
        return aBoolean;
    }

    @Override
    public void updateUserInfo(UserInfoVo userInfoVo) {
        Boolean aBoolean = usersMapper.updateUserInfo(userInfoVo);
        if (!aBoolean) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(504).setMessage("注册出了点小插曲，请稍候重试"));
        }
    }

    @Override
    public List<UserDto> selectRoomUser(List<Integer> ids) {
        List<UserDto> userDtos = usersMapper.selectRoomUser(ids);
        return userDtos;
    }

    @Override
    public RoomUsersDto selectRoomUserByName(RoomUserDto roomUserDto) {
        List<UserDto> userDtos = usersMapper.selectRoomUserByName(roomUserDto.getIds(), roomUserDto.getName(),
                roomUserDto.getPage(), roomUserDto.getLimit());
        RoomUsersDto roomUsersDto = new RoomUsersDto();
        roomUsersDto.setDtos(userDtos);
        roomUsersDto.setTotal(usersMapper.selectRoomUserCount(roomUserDto.getIds(),roomUserDto.getName()));
        return roomUsersDto;
    }

    /**
     * 得到一个人简单的信息;
     *
     * @param id
     * @return
     */
    @Override
    public UserSimpleVo getUserSimpleInfo(Integer id) {
        return usersMapper.selectOneUserSimpleInfo(id);
    }

    /**
     * 搜索用户
     *
     * @param page
     * @param limit
     * @param userName
     * @param email
     * @return
     */
    @Override
    public MyPage<UserInfosVo> searchUserByNameOrEmail(Long page, Long limit, String userName, String email) {
        MyPage<UserInfosVo> myPage = new MyPage<>();
        limit = limit < 1 ? 10 : limit;
        page = page < 1 ? 0 : (page - 1) * limit;
        List<Users> users = usersMapper.searchUserByNameOrEmail(page, limit, userName, email);
        List<UserInfosVo> list = new LinkedList<>();
        for (Users user : users) {
            UserInfosVo userInfosVo = new UserInfosVo();
            userInfosVo.setUserName(user.getUserName());
            userInfosVo.setId(user.getId());
            userInfosVo.setAvatar(user.getAvatar());
            userInfosVo.setAbout(user.getAbout());
            list.add(userInfosVo);
        }
        myPage.setTotalElements(usersMapper.searchUserCountByNameOrEmail(userName, email));
        myPage.setContent(list);
        return myPage;
    }

    /**
     * 获取用户详细信息
     *
     * @param uid
     * @return
     */
    @Override
    public UserDetailsVo getUserDetails(Integer uid,Integer fid) {
        ResultVo<Map<String, Integer>> userStatus = roomClient.getUserStatus(uid, fid);
        Map<String, Integer> data = userStatus.getData();
        Integer status = data.get("status");
        UserDetailsVo userDetailsVo = new UserDetailsVo();
        Users users = usersMapper.selectById(fid);
        BeanUtil.updateProperties(users,userDetailsVo);
        userDetailsVo.setStatus(status);
        return userDetailsVo;
    }
}
